package datastructure.sort;

import java.util.Arrays;
import java.util.Random;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/30 8:52
 * @description: 归并排序
 */
public class MergeSort {
    public static void mergeSort(int[] nums, int l, int r) {
        if (l >= r) return;
        int mid = (l + r) / 2;
        mergeSort(nums, l, mid);
        mergeSort(nums, mid + 1, r);
        merge(nums, l, mid, r);
    }

    public static void merge(int[] nums, int l, int mid, int r) {
        int[] cur = new int[nums.length];
        for (int i = l; i <= r; i++) {
            cur[i] = nums[i];
        }
        int index = l;
        int i = l;
        int j = mid + 1;
        while (i <= mid && j <= r) {
            if (cur[i] < cur[j]) {
                nums[index++] = cur[i++];
            } else {
                nums[index++] = cur[j++];
            }
        }
        while (i <= mid) {
            nums[index++] = cur[i++];
        }
        while (j <= r) {
            nums[index++] = cur[j++];
        }
    }

    public static void swap(int[] nums, int x, int y) {
        int temp = nums[x];
        nums[x] = nums[y];
        nums[y] = temp;
    }

    public static void shuffle(int[] nums) {
        Random r = new Random();
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            int j = i + r.nextInt(n - i);
            swap(nums, i, j);
        }
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 4, 6, -1, -4, -10};
        shuffle(nums);
        System.out.println(Arrays.toString(nums));
        mergeSort(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }
}
